package cn.stylefeng.guns.modular.recy.utils;

import cn.hutool.core.convert.Convert;
import cn.stylefeng.guns.modular.recy.entity.Bins;
import cn.stylefeng.guns.modular.recy.service.BinsService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

@Component
public class BinsNoCreator
{
    @Autowired
    private BinsService binsService;
    private static final AtomicLong binsNo;
    private final long BEGIN_VALUE = 100000L;
    
    public long getMaxBinsNo() {
        final QueryWrapper<Bins> binsQueryWrapper = (QueryWrapper<Bins>)new QueryWrapper();
        binsQueryWrapper.select(new String[] { "max(bins_no) as maxNo" });
        final Map<String, Object> map = this.binsService.getMap(binsQueryWrapper);
        if (map == null) {
            return BEGIN_VALUE;
        }
        final Object maxNo = map.get("maxNo");
        if (maxNo == null) {
            return BEGIN_VALUE;
        }
        return Convert.toLong(maxNo);
    }
    
    public final long incrementAndGet() {
        long current;
        long next;
        do {
            current = BinsNoCreator.binsNo.get();
            if (current < BEGIN_VALUE) {
                current = this.getMaxBinsNo();
                BinsNoCreator.binsNo.set(current);
            }
            next = ((current >= Long.MAX_VALUE) ? 0L : (current + 1L));
        } while (!BinsNoCreator.binsNo.compareAndSet(current, next));
        return next;
    }
    
    static {
        binsNo = new AtomicLong();
    }
}
